package com.example.wenhua.controller;

import com.example.wenhua.common.Result;
import com.example.wenhua.entity.Course;
import com.example.wenhua.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 课程管理控制器
 */
@RestController
@RequestMapping("/api/courses")
@CrossOrigin(origins = "*")
public class CourseController {
    
    @Autowired
    private CourseService courseService;
    
    /**
     * 查询所有课程（支持筛选）
     */
    @GetMapping
    public Result<List<Course>> getAllCourses(
            @RequestParam(required = false) String cno,
            @RequestParam(required = false) String cname,
            @RequestParam(required = false) String teacher) {
        try {
            List<Course> courses = courseService.getCoursesWithFilter(cno, cname, teacher);
            return Result.success(courses);
        } catch (Exception e) {
            return Result.error("查询课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据课程号查询课程
     */
    @GetMapping("/{cno}")
    public Result<Course> getCourseByCno(@PathVariable String cno) {
        try {
            Course course = courseService.getCourseByCno(cno);
            if (course != null) {
                return Result.success(course);
            } else {
                return Result.error("课程不存在");
            }
        } catch (Exception e) {
            return Result.error("查询课程失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据教师名查询课程
     */
    @GetMapping("/teacher/{teacher}")
    public Result<List<Course>> getCoursesByTeacher(@PathVariable String teacher) {
        try {
            List<Course> courses = courseService.getCoursesByTeacher(teacher);
            return Result.success(courses);
        } catch (Exception e) {
            return Result.error("查询课程失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增课程
     */
    @PostMapping
    public Result<Void> addCourse(@RequestBody Course course) {
        try {
            boolean success = courseService.addCourse(course);
            if (success) {
                return Result.success("课程添加成功", null);
            } else {
                return Result.error("课程添加失败");
            }
        } catch (Exception e) {
            return Result.error("课程添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新课程信息
     */
    @PutMapping("/{cno}")
    public Result<Void> updateCourse(@PathVariable String cno, @RequestBody Course course) {
        try {
            course.setCno(cno);
            boolean success = courseService.updateCourse(course);
            if (success) {
                return Result.success("课程信息更新成功", null);
            } else {
                return Result.error("课程信息更新失败");
            }
        } catch (Exception e) {
            return Result.error("课程信息更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除课程
     */
    @DeleteMapping("/{cno}")
    public Result<Void> deleteCourse(@PathVariable String cno) {
        try {
            boolean success = courseService.deleteCourse(cno);
            if (success) {
                return Result.success("课程删除成功", null);
            } else {
                return Result.error("课程删除失败");
            }
        } catch (Exception e) {
            return Result.error("课程删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取课程详细信息（包含选课人数等）
     */
    @GetMapping("/{cno}/detail")
    public Result<Map<String, Object>> getCourseDetail(@PathVariable String cno) {
        try {
            Map<String, Object> detail = courseService.getCourseDetailByCno(cno);
            if (detail != null) {
                return Result.success(detail);
            } else {
                return Result.error("课程不存在");
            }
        } catch (Exception e) {
            return Result.error("查询课程详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取课程统计信息
     */
    @GetMapping("/{cno}/stats")
    public Result<Map<String, Object>> getCourseStats(@PathVariable String cno) {
        try {
            Map<String, Object> stats = courseService.getCourseStatsByCno(cno);
            if (stats != null) {
                return Result.success(stats);
            } else {
                return Result.error("课程不存在");
            }
        } catch (Exception e) {
            return Result.error("查询课程统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取课程平均分
     */
    @GetMapping("/{cno}/average")
    public Result<BigDecimal> getCourseAverageGrade(@PathVariable String cno) {
        try {
            BigDecimal average = courseService.getCourseAverageGrade(cno);
            return Result.success(average);
        } catch (Exception e) {
            return Result.error("查询课程平均分失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有课程的平均分统计
     */
    @GetMapping("/statistics/average")
    public Result<List<Map<String, Object>>> getAllCoursesAverageGrade() {
        try {
            List<Map<String, Object>> statistics = courseService.getAllCoursesAverageGrade();
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("查询课程平均分统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有课程的整体平均成绩
     */
    @GetMapping("/average-score")
    public Result<BigDecimal> getOverallAverageScore() {
        try {
            BigDecimal overallAverage = courseService.getOverallAverageScore();
            return Result.success(overallAverage);
        } catch (Exception e) {
            return Result.error("查询整体平均成绩失败：" + e.getMessage());
        }
    }
}